package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2021-11-22
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Autowired
    private BCryptPasswordEncoder encoder;

    /**
     * admin平台登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> login(AdUserLoginDto dto) {
//        设置查询条件
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("name",dto.getName());
        queryWrapper.lambda().eq(AdUser::getName,dto.getName());
//        登录用户名查询用户信息
        AdUser adUser = getOne(queryWrapper);
        if(adUser == null){
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
//        验证用户名密码
        String encodedPwd = adUser.getPassword();
        boolean b = encoder.matches(dto.getPassword(), encodedPwd);
        if (!b) {
//            密码验证失败
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
//        生成Token
        String token = JwtUtils.generateTokenExpireInMinutes(adUser.getId(), 60);
        Map<String,Object> map = new HashMap<>();
        map.put("user", BeanHelper.copyProperties(adUser, AdUserDto.class));
        map.put("token",token);
        return map;
    }
}
